﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using BabyShop.WebSite.Exts.Attributes;
using BabyShop.WebSite.Models;
using BabyShop.WebSite.Services;

namespace BabyShop.WebSite.Controllers
{
    public class AccountController : BaseController
    {
        private readonly UserService _userServices = new UserService();

        [GeneralPermission]
        public ActionResult LogOn() {
            return View();
        }

        [HttpPost]
        [GeneralPermission]
        public ActionResult LogOn(LogOnModel model, string returnUrl) {
            if (ModelState.IsValid) {
                if (_userServices.ValidateUser(model.Email, model.Password)) {
                    CurrentStore.Add(_userServices.GetUserByAccount(model.Email));
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) {
                        return Redirect(returnUrl);
                    }
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", @"The user name or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOff() {
            CurrentStore.Clear();
            return RedirectToAction("Index", "Home");
        }

        [GeneralPermission]
        public ActionResult Register() {
            return View();
        }

        [HttpPost]
        [GeneralPermission]
        public ActionResult Register(RegisterModel model) {
            if (ModelState.IsValid) {

                bool isSucc = _userServices.CreateUser(model.Email, model.Password);

                if (isSucc) {
                    CurrentStore.Add(_userServices.GetUserByAccount(model.Email));
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "User Register Error");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePassword() {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model) {
            if (ModelState.IsValid) {
                bool changePasswordSucceeded;
                try {
                    User currUser = CurrentStore.Read<User>();
                    changePasswordSucceeded = _userServices.ChangeUserPassword(
                        model.OldPassword, 
                        model.NewPassword,
                        ref currUser);
                }
                catch (Exception) {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded) {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult ChangePasswordSuccess() {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus) {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus) {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
